package com.ben.utils.flow

import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import java.util.concurrent.atomic.AtomicBoolean

/**
 * Author: bin.yang
 * Maintainer: bin.yang
 * Date: 2021/10/20
 * Copyright: 2021 Inc. All rights reserved.
 * Desc:
 */
class XStateFlow<T>(private val flow: StateFlow<T>) {

    private val initStatus = AtomicBoolean(false)

    @InternalCoroutinesApi
    suspend fun collect(collector: FlowCollector<T>) {
        if (initStatus.compareAndSet(false, true))
            flow.collect(collector)
    }

    suspend fun collectLatest(action: suspend (value: T) -> Unit) {
        if (initStatus.compareAndSet(false, true))
            flow.collectLatest(action)
    }

    @InternalCoroutinesApi
    suspend fun first(predicate: suspend (T) -> Boolean) {
        if (initStatus.compareAndSet(false, true))
            flow.first(predicate)
    }

    fun getValue(): T {
        return flow.value
    }
}
